package com.forum.model.dao;

import java.util.List;

import org.hibernate.Session;

import com.forum.model.pojo.LiveNews;
import com.forum.model.util.SessionManager;

public class LiveNewsDAO implements GenericDAO<LiveNews, Long> {

	private Session session;

	@Override
	public boolean insert(LiveNews liveNews) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(liveNews);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean update(LiveNews liveNews) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(liveNews);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean delete(LiveNews liveNews) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(liveNews);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public LiveNews getObjectById(Long id) {
		LiveNews liveNews = null;
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			liveNews = (LiveNews) session.get(LiveNews.class, id);
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return liveNews;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<LiveNews> getAll() {
		List<LiveNews> all = null;

		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<LiveNews>) session.createQuery("from LiveNews").list();
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}

		return all;
	}
}
